package com.fairy.sso.client.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.fairy.sso.core.NetHelp;
import com.fairy.sso.core.SSOConstants;
import com.fairy.sso.exception.SSOException;

public class SSOClientFilterHelp {
	private static Logger log = Logger.getLogger(SSOClientFilterHelp.class);
	public static void trace(Logger log,String str)
	{
		String envType=getProperty("env_type");
		if(null!=envType&&envType.equals("dev"))
		{
			System.out.println(str);
		}
		
		log.info(str);
	}
	
	public static String getProperty(String key)
	{
		String value="";
		try {
			ResourceBundle resource = ResourceBundle.getBundle("sso");
			value=resource.getString(key);
		} catch (Exception e2) {
			e2.printStackTrace();
		}
		return value;
	}
	
	public static String getSsoConfigUrl(String configUrl) throws SSOException 
	{
		//"sso.server.url"
		//String sso_server_url=resource.getString(configUrl);
		String  sso_server_url=SSOClientFilterHelp.getProperty(configUrl);
		if(sso_server_url.endsWith("/"))
		{
			sso_server_url=sso_server_url.substring(0, sso_server_url.length()-1);
		}
		
		if(sso_server_url.startsWith("http://")||sso_server_url.startsWith("https://"))
		{
			if(sso_server_url.endsWith("/"))
			{
				sso_server_url=sso_server_url.substring(0, sso_server_url.length()-1);
			}
		}
		else
		{
			throw new SSOException(configUrl+"  配置错误,缺少http://或者https://");
	
		}
		return sso_server_url;
	}
	public static String getCookieSetDomain(String ssoCientIp, String domain) 
	{
		boolean isIp=NetHelp.isIP(domain);
		if(!isIp)
		{
			trace(log, "<------ domain is not ip,"+domain+"---------->");
			domain="."+domain;
		}
		else
		{
			domain=ssoCientIp;
		    trace(log, "<---------domain is  ip,"+domain+"-------------->");
		}
		return domain;
	}
	
	public static boolean judgeStaticUrl(String uri, String[] splitAddress) 
	{
		boolean bls=false;
    	for(String str:splitAddress)
    	{
        	if(uri.contains("."+str))
        	{
        		bls=true;
        		break;
        	}
    	}
    	if(!bls)
    	{
            if(uri.contains(".css") ||uri.contains("removeCookie.sso")||uri.contains("setCookie.sso")||bls==true)
            {
            	bls=true;
            }
            else
            {
            	if(uri.contains(".js")&&!uri.contains(".jsp"))
            	{
            		bls=true;
            	}
            }
    	}
		return bls;
	}
	
	public static String getReqUrlWithParam(HttpServletRequest request,boolean isFilter) throws UnsupportedEncodingException 
	{
		String params = request.getQueryString();//返回请求行中的参数部分
		String url = "";
		String urls=request.getRequestURL().toString();
		trace(log,"O(∩_∩)Orequest.getRequestURL()=========="+urls+"======================");
		

		
		if(null==params||params.equals(""))
		{
			url = URLEncoder.encode(urls, "UTF-8");
           	trace(log,"new log getReqUrlWithParam-------------------"+url+"-------------------------");
		}
		else
		{
			//params=params.toLowerCase();
			String params_url="";
			if(isFilter)
			{
				params = filterParams(request, params,SSOConstants.TICKET);
				params = filterParams(request, params,"ssoFlag");
				params = filterParams(request, params,"ssoCrossDomain");
				HashMap<String,String>map=new HashMap<String,String>();
				filterURL(params, map);
				params_url=map.get("params_url")==null?"":map.get("params_url");
	           	trace(log,"new log getReqUrlWithParam-------------------"+params_url+"-------------------------");
			}

            if(null!=params_url&&!params_url.equals(""))
            {
            	url = URLEncoder.encode(urls+"?"+params_url, "UTF-8");
            }
            else
            {
            	url = URLEncoder.encode(urls, "UTF-8");
            }
			
		}
		trace(log,"O(∩_∩)O获得完整URL====================="+url+"=====================");
		
		return url;
	}
	private static void filterURL(String urls,HashMap<String,String>map)
	{
		//String temp="";
		if(urls.endsWith("&"))
	    {
	    	int endIndex=urls.lastIndexOf("&");
	    	urls=urls.substring(0, endIndex);
	    	map.put("params_url", urls);
	    	filterURL(urls,map);
	    }
		if(urls.startsWith("&"))
	    {
	    	int startIndex=urls.indexOf("&");
	    	urls=urls.substring(startIndex+1);
	    	map.put("params_url", urls);
	    	filterURL(urls,map);
	    }
	}
	private static String filterParams(HttpServletRequest request, String params,String paramName) 
	{
		if(params.contains(paramName+"="))
		{
			String ticketValue=request.getParameter(paramName);
			params=params.replace(paramName+"="+ticketValue, "");
		}
		return params;
	}
	
	public static void repJson(HttpServletRequest request, HttpServletResponse response, String json)
			throws UnsupportedEncodingException, IOException 
	{
		trace(log,"::::::::::::::::::::::::::::::::::::::ajax请求,不做跳转,返回报文:"+json+":::::::::::::::::::::::::::::::::::::::::");

		trace(log,":::::::::::::::::::::::::::::::::::::::还未执行response,"+request.getRequestURL()+":::::::::::::::::::::::::::::::::::::::::");
		
		response.setContentType("application/json; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		try{
		    out.println(json);
		    out.flush();
		    out.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
		    out.flush();
		    out.close();
		}
	}
	public static String getConfigUrl(String propertyKey)
	{
		String val="";
		try {
			val = SSOClientFilterHelp.getSsoConfigUrl(propertyKey);
		} catch (SSOException e2) {
			e2.printStackTrace();
		}
		return val;
	}
}
